package com.android.bookgarden.tabfragment;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.bookgarden.R;
import com.android.bookgarden.adapter.NewsFragmentPagerAdapter;
import com.android.bookgarden.base.BaseFragment;
import com.android.bookgarden.bean.BtItem;
import com.android.bookgarden.ui.SearchActivity;
import com.android.bookgarden.utli.Utlis;
import com.flyco.tablayout.SlidingTabLayout;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Created by zouqh on 2018/3/19.
 * 首页
 */

public class Tab1Fragment extends BaseFragment {

//    @BindView(R.id.tab)
//    TabLayout tab;
    @BindView(R.id.mRadioGroup_content)
    LinearLayout mRadioGroupContent;
    @BindView(R.id.hs_activity_tabbar)
    HorizontalScrollView mColumnHorizontalScrollView;
    //    @BindView(R.id.category_line)
//    View categoryLine;
    @BindView(R.id.viewpager)
    ViewPager mViewPager;
    @BindView(R.id.cursor)
    ImageView cursor;
    @BindView(R.id.allFenl)
    ImageView allFenl;
    Unbinder unbinder;

//    @BindView(R.id.tabs)
//    TabLayout tabs;
//    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.tl_3)
    SlidingTabLayout tl3;
    @BindView(R.id.searchLayout)
    LinearLayout searchLayout;
//    @BindView(R.id.toolbar)
//    Toolbar toolbar;


//    private TabAdapter adapter;
    /**
     * 当前选中的栏目
     */
    private int columnSelectIndex = 0;

    /**
     * 屏幕宽度
     */
    private int mScreenWidth = 0;
    /**
     * Item宽度
     */
    private int mItemWidth = 0;
    //动画图片宽度
    private int bmpW;
    //动画图片偏移量
    private int offset = 0;
    private int position_one;
    private int position_two;

    private ArrayList<Fragment> fragments = new ArrayList<Fragment>();
    public ArrayList<BtItem> item = new ArrayList<BtItem>();

    private NewsFragmentPagerAdapter mAdapetr;
    public static Tab1Fragment tab1Fragment = null;

    @Override
    protected int getLayoutId() {
        return R.layout.tab1_fragment;
    }

    @Override
    protected void initView() {
        tab1Fragment = this;
        mScreenWidth = Utlis.getWindowsWidth(getActivity());
        mItemWidth = mScreenWidth / 5;// 一个Item宽度为屏幕的1/5
        item.add(new BtItem("", "推荐"));
        item.add(new BtItem("", "唱歌"));
        item.add(new BtItem("", "舞蹈"));
        item.add(new BtItem("", "钢琴"));
        item.add(new BtItem("", "小提琴"));
        item.add(new BtItem("", "画画"));
        initTabColumn();
        initFragment();
        searchLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(SearchActivity.class);
            }
        });
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    /**
     * 初始化动画
     */
    private void InitImageView() {
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);

        // 获取分辨率宽度
        int screenW = dm.widthPixels;
        bmpW = (screenW / 5);

        //设置动画图片宽度
        setBmpW(cursor, bmpW);
        offset = 0;

        //动画图片偏移量赋值
        position_one = (int) (screenW / 3.0);
        position_two = position_one * 2;

    }

    /**
     * 设置动画图片宽度
     *
     * @param mWidth
     */
    private void setBmpW(ImageView imageView, int mWidth) {
        ViewGroup.LayoutParams para;
        para = imageView.getLayoutParams();
        para.width = mWidth;
        imageView.setLayoutParams(para);
    }

    /**
     * 初始化Column栏目项
     */
    private void initTabColumn() {
        mRadioGroupContent.removeAllViews();
        int count = item.size();
        // mColumnHorizontalScrollView.setParam(this, mScreenWidth,
        // mRadioGroupContent, shade_left, shade_right, ll_more_columns,
        // rl_column);
        for (int i = 0; i < count; i++) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    mItemWidth, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.leftMargin = 5;
            params.rightMargin = 5;
            // TextView localTextView = (TextView)
            // mInflater.inflate(R.layout.column_radio_item, null);
            TextView columnTextView = new TextView(getActivity());
            if (i == 0) {
                columnTextView.setTextSize(20);
                TextPaint paint = columnTextView.getPaint();
                paint.setFakeBoldText(true);
            }
//            columnTextView.setTextAppearance(this,
//                    R.style.top_category_scroll_view_item_text);
            // localTextView.setBackground(getResources().getDrawable(R.drawable.top_category_scroll_text_view_bg));
            columnTextView.setGravity(Gravity.CENTER);
            columnTextView.setPadding(5, 5, 5, 5);
            columnTextView.setId(i);
            columnTextView.setText(item.get(i).getName());
            columnTextView.setTextColor(getResources().getColorStateList(
                    R.color.bof_color));
            if (columnSelectIndex == i) {
                columnTextView.setSelected(true);
            }
            columnTextView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    for (int i = 0; i < mRadioGroupContent.getChildCount(); i++) {
                        View localView = mRadioGroupContent.getChildAt(i);
                        if (localView != v)
                            localView.setSelected(false);
                        else {
                            localView.setSelected(true);
                            mViewPager.setCurrentItem(i);
                        }
                    }
                    // Toast.makeText(getApplicationContext(),
                    // item.get(v.getId()).getName(),
                    // Toast.LENGTH_SHORT).show();
                }
            });
            mRadioGroupContent.addView(columnTextView, i, params);
        }
    }

    /**
     * 初始化Fragment
     */
    private void initFragment() {
        fragments.clear();// 清空
        int count = item.size();
        for (int i = 0; i < count; i++) {
            Bundle data = new Bundle();
//            data.putString("url", item.get(i).getUrl());
//            data.putInt("id", Integer.parseInt(item.get(i).getId()));
            HomeTabFragment newfragment =HomeTabFragment.newInstance(i,item.get(i).getId());
            newfragment.setArguments(data);
            fragments.add(newfragment);
        }
        mAdapetr = new NewsFragmentPagerAdapter(getActivity().getSupportFragmentManager(),
                fragments);
        mViewPager.setOffscreenPageLimit(count);
        mViewPager.setAdapter(mAdapetr);
        mViewPager.setOnPageChangeListener(pageListener);
//        tl3.setViewPager(mViewPager);
        //将TabLayout和ViewPager关联起来。
//        tab.setupWithViewPager(mViewPager);
//        //设置可以滑动
//        tab.setTabMode(TabLayout.MODE_SCROLLABLE);
    }

    /**
     * ViewPager切换监听方法
     */
    public ViewPager.OnPageChangeListener pageListener = new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int position) {
            // TODO Auto-generated method stub
            mViewPager.setCurrentItem(position);
            selectTab(position);
        }
    };

    /**
     * 选择的Column里面的Tab
     */
    private void selectTab(int tab_postion) {
        columnSelectIndex = tab_postion;
        for (int i = 0; i < mRadioGroupContent.getChildCount(); i++) {
            View checkView = mRadioGroupContent.getChildAt(tab_postion);
            int k = checkView.getMeasuredWidth();
            int l = checkView.getLeft();
            int i2 = l + k / 2 - mScreenWidth / 2;
            // rg_nav_content.getParent()).smoothScrollTo(i2, 0);
            mColumnHorizontalScrollView.smoothScrollTo(i2, 0);
            // mColumnHorizontalScrollView.smoothScrollTo((position - 2) *
            // mItemWidth , 0);
        }
        // 判断是否选中
        for (int j = 0; j < mRadioGroupContent.getChildCount(); j++) {
            View checkView = mRadioGroupContent.getChildAt(j);
            boolean ischeck;
            TextView tte = (TextView) checkView;
            if (j == tab_postion) {
                ischeck = true;

                tte.setTextSize(20);
                TextPaint paint = tte.getPaint();
                paint.setFakeBoldText(true);

            } else {
                ischeck = false;
                tte.setTextSize(14);
                TextPaint paint = tte.getPaint();
                paint.setFakeBoldText(false);
            }
            checkView.setSelected(ischeck);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
